package cn.element.chatroom.server.handler;

import cn.element.chatroom.message.LoginRequestMessage;
import cn.element.chatroom.message.LoginResponseMessage;
import cn.element.chatroom.server.service.UserServiceFactory;
import cn.element.chatroom.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        String username = msg.getUsername();
        String password = msg.getPassword();
        boolean flag = UserServiceFactory.getUserService().login(username, password);
        LoginResponseMessage response;

        if (flag) {
            SessionFactory.getSession().bind(ctx.channel(), username);
            response = new LoginResponseMessage(true, "登录成功!");
        } else {
            response = new LoginResponseMessage(true, "用户名或密码错误!");
        }

        ctx.writeAndFlush(response);
    }
}
